package com.bytecub.udp.service.parser;

import com.bytecub.common.domain.dto.response.device.DevicePageResDto;
import com.bytecub.common.domain.message.DeviceDownMessage;
import com.bytecub.common.enums.DevTypeEnum;
import com.bytecub.mdm.cache.IDownMessageCache;
import com.bytecub.mdm.service.IDeviceService;
import com.bytecub.protocol.domain.bo.DeviceProductBo;
import com.bytecub.protocol.service.IProtocolUtilService;
import com.bytecub.storage.IMessageReplyService;
import com.bytecub.storage.entity.MessageReplyEntity;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * * ByteCub.cn. * Copyright (c) 2020-2021 All Rights Reserved. * * @author bytecub@163.com songbin
 * * @Date 2021/4/6 Exp $$
 */
@Slf4j
@Service
public class DownMessageParser {
    @Autowired IDownMessageCache downMessageCache;
    @Autowired IProtocolUtilService protocolUtilService;
    @Autowired IMessageReplyService messageReplyService;
    @Autowired IDeviceService deviceService;

    public byte[] encode(String deviceCode) {
        try {
            List<DeviceDownMessage> downMessages = this.serviceData(deviceCode);
            if (CollectionUtils.isEmpty(downMessages)) {
                return "".getBytes();
            }
            for (DeviceDownMessage item : downMessages) {
                this.processSubDevice(deviceCode, item);
            }
            DeviceProductBo deviceProductBo =
                    protocolUtilService.queryInstanceByDeviceCode(deviceCode);
            byte[] ret = deviceProductBo.getBaseProtocol().encodeBatch(deviceCode, downMessages);
            this.saveRet(downMessages);
            return null == ret ? "".getBytes() : ret;
        } catch (Exception e) {
            log.warn("UDP协议下发数据到设备[{}]异常", deviceCode, e);
            return "".getBytes();
        }
    }

    private List<DeviceDownMessage> serviceData(String deviceCode) {
        List<DeviceDownMessage> list = downMessageCache.downMessageReader(deviceCode);
        return list;
    }

    /** 对于UDP协议 只要下发了 就认为成功了 */
    public void saveRet(List<DeviceDownMessage> downMessages) {
        for (DeviceDownMessage deviceMessage : downMessages) {
            try {
                MessageReplyEntity messageReplyEntity = new MessageReplyEntity();
                messageReplyEntity.setMessageId(deviceMessage.getMessageId());
                messageReplyEntity.setBody("已下发[UDP只管下发]");
                messageReplyEntity.setDeviceCode(deviceMessage.getDeviceCode());
                messageReplyEntity.setDevTimestamp(new Date());
                messageReplyEntity.setProductCode(deviceMessage.getProductCode());
                messageReplyEntity.setTimestamp(new Date());
                messageReplyEntity.setStatus(200);
                messageReplyService.create(messageReplyEntity);
            } catch (Exception e) {
                log.warn("", e);
                continue;
            }
        }
    }

    /** 网关子设备相关处理 */
    private void processSubDevice(String deviceCode, DeviceDownMessage deviceDownMessage) {
        DevicePageResDto devicePageResDto = deviceService.queryByDevCode(deviceCode);

        String nodeType = devicePageResDto.getNodeType();
        if (DevTypeEnum.SUB.getType().equals(nodeType)) {
            deviceDownMessage.setSubFlag(true);
            deviceDownMessage.setGwDeviceCode(devicePageResDto.getGwDevCode());
        }
    }
}
